// pages/dynamicDetail/index.js
const util = require('../../utils/util')
const {
  envList
} = require('../../envList.js');
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    defaultAvatarUrl,
    dynamicData: {},
    commentlist: [],
    is_myDyn: false,
    writeComment: false,
    anonymous: false,
    showReplyinput: false,
    time: '',
    id: '',
    newcomment: '',
    newreply: '',
    openid: '',
    avatarUrl: '',
    itemAverageHeight: 500, //每条数据平均高度，为确保能滚到底部，可以设置大一些
    scrollTop: 1000,
    inputBottom: 0,
    count_approval: 0,
    love_num:0
  },




  

/**
 * 生命周期函数--监听页面加载
 */
onLoad: function (options) {
  const id = options.id;
  const openid = wx.getStorageSync('OPENID'),
    avatarUrl = wx.getStorageSync('AVATARURL'),
    nickname = wx.getStorageSync('NICKNAME'),
    userInfo = wx.getStorageSync('userInfo')
  this.getdynamic(id)
  this.getcommentlist(id)
  //获取当前浏览记录
  let saw_dynamic = wx.getStorageSync('SAWDYN') || []
  let index = saw_dynamic.indexOf(id)
  if (index !== -1) {
    saw_dynamic.splice(index, 1)
  }
  saw_dynamic.push(id)
  wx.setStorageSync('SAWDYN', saw_dynamic)
  console.log('1')
  this.setData({
    id: id,
    openid: openid,
    avatarUrl: userInfo.avatarUrl || avatarUrl,
    nickname: userInfo.nickname || nickname
  })
},

/**
 * 生命周期函数--监听页面初次渲染完成
 */
onReady: function () {

},

/**
 * 生命周期函数--监听页面显示
 */
onShow: function () {
  const id = this.data.id;
  console.log('1')
},

/**
 * 生命周期函数--监听页面隐藏
 */
onHide: function () {

},
getdynamic(id) {
  wx.cloud.database().collection('dynamiclist').where({
    _id: id
  }).get({
    success: (res) => {
      let t = util.formatTime(new Date(res.data[0].time))
      let dynamicData = res.data[0]
      dynamicData.content = dynamicData.content.split('&hc').join('\n')
      this.setData({
        dynamicData: dynamicData,
        time: t
      })

      if (res.data[0]._openid == wx.getStorageSync('OPENID')) {
        this.setData({
          is_myDyn: true
        })
      }
      this.getlike(id)
      this.getlikeNumber(id)
    },
    fail: (err) => {
      console.err(err)
    }
  })

},
changeapproval(e) {
  let approval = e.currentTarget.dataset.approval
  let dynamicData = this.data.dynamicData
  dynamicData.approval = !approval
  this.setData({
    dynamicData: dynamicData
  })
  let that = this;
  if (this.data.dynamicData.approval == true) {
    this.setData({
      count_approval: that.data.count_approval + 1
    })
  } else {
    this.setData({
      count_approval: that.data.count_approval - 1
    })
  }
  wx.cloud.init({
    env: 'cloud1-5glocnmp62950062'
  })
  wx.cloud.callFunction({
    name: 'changeApproval',
    data: {
      dynamicid: dynamicData._id
    },
    success: res => {}
  })
},
changelike(e) {
  let like = e.currentTarget.dataset.like
  let dynamicData = this.data.dynamicData
  dynamicData.like = !like
  this.setData({
    dynamicData: dynamicData
  })
  
  wx.cloud.init({
    env: 'cloud1-5glocnmp62950062'
  })
  wx.cloud.callFunction({
    name: 'changeLove',
    data: {
      dynamicid: dynamicData._id
    },
    success: res => {}
  })
  //修改点赞次数
  let that = this;
  if (like == true) {
    this.setData({
      love_num: that.data.love_num - 1
    })
  } else {
    this.setData({
      love_num: that.data.love_num + 1
    })
  }
},
editDyn: function () {
  wx.navigateTo({
    url: `/pages/dynamicForm/index?editid=${this.data.dynamicData._id}`,
  })
},
deleteDyn: function () {
  wx.showModal({
    cancelColor: 'cancelColor',
    content: '请您确认删除此条动态',
    success: (res) => {
      if (res.confirm) {
        wx.cloud.database().collection('dynamiclist').doc(this.data.dynamicData._id).remove({
          success: () => {
            wx.showToast({
              title: '删除成功',
            })
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 500);
          }
        })
      } else {
        console.log('用户点击取消')
      }
    }
  })
},
getlike(id) {
  let openid = wx.getStorageSync('OPENID')
  wx.cloud.database().collection('loveList').where({
    dynamicid: id,
    openid: openid
  }).get({
    success: (res) => {
      let dynamicData = this.data.dynamicData
      dynamicData.like = res.data[0].status
      this.setData({
        dynamicData: dynamicData
      })
    }
  })
  wx.cloud.database().collection('approvalList').where({
    dynamicid: id,
    openid: openid
  }).get({
    success: (res) => {
      let dynamicData = this.data.dynamicData
      dynamicData.approval = res.data[0].status
      this.setData({
        dynamicData: dynamicData
      })
    }
  })
},
getlikeNumber(id){
  wx.cloud.database().collection('loveList').where({
    dynamicid: id,
    status:true
  }).count({
    success:res=>{
      this.setData({
        love_num: res.total
      })
    }
  })
  wx.cloud.database().collection('approvalList').where({
    dynamicid: id,
    status:true
  }).count({
    success:res=>{
      this.setData({
        count_approval: res.total
      })
    }
  })
},
bindComment(e) {
  this.setData({
    newcomment: e.detail.value
  })
},

// 添加评论
addcomment(e) {
  let _id = this.data.dynamicData._openid;
  let newcomment = e.detail.value.newcomment;
  let title=this.data.dynamicData.title;
  let commentuser=this.data.nickname;
  let time = util.formatTime(new Date(Date.now()))
  let userInfo = wx.getStorageSync('userInfo')
  let NICKNAME = wx.getStorageSync('NICKNAME'),
    AVATARURL = wx.getStorageSync('AVATARURL')
  if (newcomment === '') {
    wx.showToast({
      title: '不可发送空内容！',
      icon: 'none'
    })
    return
  }
  this.sendMsg(_id, title, newcomment, time,commentuser);
  wx.cloud.database().collection('comments').add({
    data: {
      dynamicid: this.data.id,
      nickname: this.data.anonymous ? '匿名用户' : (userInfo.nickname || NICKNAME),
      avatarUrl: this.data.anonymous ? defaultAvatarUrl : (userInfo.avatar || AVATARURL),
      content: newcomment.split('\n').join('&hc'),
      time: Date.now(),

    },
    success: res => {
      wx.showToast({
        title: '发表成功',
      })
      this.getcommentlist(this.data.id);
      
      this.setData({
        newcomment: ''
      })
    }
  })
},
// 被评论发送弹窗

sendMsg(_id, title, text, time, commentuser) {
  
    wx.requestSubscribeMessage({
      tmplIds: ["Z8kjov8pifwoQgS4VDEN41oWU73mpUuuAR7Q2ANV1ac"],
    }).then(res => {
      console.log("获取消息推送授权成功", res);
    }).catch(err => {
      console.log("获取消息推送授权失败", err);
    })
  
  wx.cloud.init({
    env: 'cloud1-5glocnmp62950062'
  })
  wx.cloud.callFunction({
    name: "sendMessage", //调用发送消息的云函数
    data: {
      _id: _id, 
      title: title,
      text: text,
      time: time,
      commentuser: commentuser
    }
  }).then(res => {
    console.log("发送消息成功", res);
  }).catch(err => {
    console.log("发送消息失败", err);
  })
},
getcommentlist(id) {
  wx.cloud.database().collection('comments').where({
    dynamicid: id
  }).get({
    success: res => {
      console.log(res)
      this.setData({
        commentlist: res.data.map(item => {
          item.time = util.formatTime(new Date(item.time))
          item.content = item.content.split('&hc').join('\n')
          return item
        })
      })
    }
  })
},
changeWrite() {
  let writeComment = !this.data.writeComment
  this.setData({
    writeComment: writeComment
  })
},
deleteComment(e) {
  let commentid = e.currentTarget.dataset.commentid
  wx.showModal({
    cancelColor: '#00000',
    title: '提示',
    content: '确定删除该条评论吗？',
    success: (result) => {
      if (result.confirm) {
        wx.cloud.database().collection('comments').where({
          _id: commentid
        }).remove({
          success: res => {
            wx.showToast({
              title: '删除成功',
            })
            this.getcommentlist(this.data.id)
          }
        })
      }
    },
    fail: () => {
      return false
    },
    complete: () => {},
  })

},
anonymousChange() {
  let anonymous = !this.data.anonymous
  this.setData({
    anonymous: anonymous
  })
},
//点击事件  
clickImg: function (e) {
  let urls = this.data.dynamicData.picCloudurl
  let current = e.currentTarget.dataset.imgUrl
  wx.previewImage({
    urls, //需要预览的图片http链接列表，注意是数组
    current, // 当前显示图片的http链接，默认是第一个
    success: function (res) {},
    fail: function (res) {},
    complete: function (res) {},
  })
},
//回复评论
replyComment: function (e) {
  let commentindex = e.currentTarget.dataset.commentindex
  let commentlist = this.data.commentlist
  commentlist[commentindex].showReplyinput = true
  this.setData({
    commentlist: commentlist
  })

},
bindKeyInput: function (e) {
  this.setData({
    inputValue: e.detail.value
  })
},
closeReplyinput: function (e) {
  let commentindex = e.currentTarget.dataset.commentindex
  let commentlist = this.data.commentlist
  commentlist[commentindex].showReplyinput = false
  this.setData({
    commentlist: commentlist
  })
},
submitReply: function (e) {
  let userInfo = wx.getStorageSync('userInfo')
  let NICKNAME = wx.getStorageSync('NICKNAME'),
    AVATARURL = wx.getStorageSync('AVATARURL')
  let replycontent = e.detail.value
  let comment = e.currentTarget.dataset.commentitem
  let replylist = comment.replylist || []
  replylist.push({
    content: replycontent,
    _openid: this.data.openid,
    avatar: userInfo.avatar || AVATARURL,
    nickname: userInfo.nickname || NICKNAME,
    time: util.formatTime(new Date(Date.now()))
  })
  wx.cloud.database().collection('comments').doc(comment._id).update({
    data: {
      replylist: replylist
    },
    success: res => {
      this.getcommentlist(this.data.id)
    }
  })
},
deleteReply: function (e) {
  let replyindex = e.currentTarget.dataset.replyindex,
    comment = e.currentTarget.dataset.commentitem
  console.log(replyindex)
  let replylist = comment.replylist
  replylist.splice(replyindex, 1)
  console.log(replylist)
  wx.cloud.database().collection('comments').doc(comment._id).update({
    data: {
      replylist: replylist
    },
    success: res => {
      wx.showToast({
        title: '删除成功',
        icon: 'none'
      })
      this.getcommentlist(this.data.id)
    }
  })
},
/**
 * 生命周期函数--监听页面卸载
 */
onUnload: function () {

},


/**
 * 页面上拉触底事件的处理函数
 */
onReachBottom: function () {

},

/**
 * 用户点击右上角分享
 */
onShareAppMessage: function () {

}
})